package micencats;

import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.SwingUtilities;

public class Main {

	/**
	 * The application frame.
	 */
	private JFrame jframe;

	/**
	 * The map engine component.
	 */
	private MapEngine mapEngine;

	// The cell resources
	private ImageIcon back;
	private ImageIcon wall;
	private ImageIcon in;
	private ImageIcon out;
	// The sprites resources
	private ImageIcon mouseSouthEast;
	private ImageIcon catSouthWest;

	/**
	 * Executes the necessary actions to display the application frame.
	 */
	public void showMainFrame() {

		// Prepare a runnable to work on Event Dispatch Thread
		Runnable runnable = new Runnable() {

			@Override
			public void run() {
				loadImages();
				createMapEngine();
				createMainFrame();
			}

		};

		// Execute the actions
		if (SwingUtilities.isEventDispatchThread()) {
			runnable.run();
		} else {
			SwingUtilities.invokeLater(runnable);
		}
	}

	private void createMainFrame() {
		jframe = new JFrame("Mice'n'Cats demo");
		jframe.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		jframe.getContentPane().add(mapEngine);
		jframe.pack();
		jframe.setVisible(true);
	}

	private void createMapEngine() {
		mapEngine = new MapEngine(8, 8, back);
		// Draw peripheral walls
		for (int j = 0; j < 8; j++) {
			mapEngine.setCell(0, j, wall);
			mapEngine.setCell(7, j, wall);
			mapEngine.setCell(j, 0, wall);
			mapEngine.setCell(j, 7, wall);
		}
		mapEngine.setCell(1, 4, wall);
		mapEngine.setCell(2, 4, wall);
		mapEngine.setCell(3, 4, wall);
		// Draw in/out
		mapEngine.setCell(1, 1, in);
		mapEngine.setCell(6, 6, out);
		// Draw sprites
		mapEngine.setSprite(1, 2, mouseSouthEast);
		mapEngine.setSprite(4, 5, catSouthWest);
	}

	private void loadImages() {
		// Using Class.getResource() to load images from classpath
		Class<Main> mainClass = Main.class;
		// Cells
		back = new ImageIcon(mainClass.getResource("/back.gif"));
		wall = new ImageIcon(mainClass.getResource("/wall.gif"));
		in = new ImageIcon(mainClass.getResource("/in.gif"));
		out = new ImageIcon(mainClass.getResource("/out.gif"));
		// Sprites
		mouseSouthEast = new ImageIcon(mainClass.getResource("/mouse_se.gif"));
		catSouthWest = new ImageIcon(mainClass.getResource("/cat_sw.gif"));
	}

	/**
	 * Program entry method.
	 * 
	 * @param args not used.
	 */
	public static void main(String[] args) {
		Main main = new Main();
		main.showMainFrame();
	}
}
